<%@Page Language="VB"%>

<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.SqlClient" %>
<%@Import Namespace="System.Xml" %>

<%@ Register TagPrefix="wrox" TagName="connect" Src="..\global\connect-strings.ascx" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head>
<title>Reading XML Direct From SQL Server With An XmlReader</title>
<!-- #include file="..\global\style.inc" -->
</head>
<body bgcolor="#ffffff">
<span class="heading">Reading XML Direct From SQL Server With An XmlReader</span><hr />
<!--------------------------------------------------------------------------->

<%'-- insert connection string script --%>
<wrox:connect id="ctlConnectStrings" runat="server"/>

<div>Connection string: <b><span id="outConnect" runat="server"></span></b></div>
<div>SELECT command: <b><span id="outSelect" runat="server"></span></b></div><p />
<div id="outError" runat="server" />
<div id="outResult" runat="server" />

<script language="vb" runat="server">

Sub Page_Load()

   'get connection string from ..\global\connect-strings.ascx user control
   Dim strConnect As String
   strConnect = ctlConnectStrings.SQLConnectionString
   outConnect.InnerText = strConnect 'and display it

   'specify the SELECT statement to extract the data as an
   'XML document using SQL Server 2000's "FOR XML" option
   Dim strSelect As String
   strSelect = "SELECT * FROM BookList WHERE ISBN LIKE '1861003%' FOR XML AUTO"
   outSelect.InnerText = strSelect   'and display it

   'create a new StringBuilder to hold the results
   Dim objStrBuilder As New StringBuilder()

   Try

      'create a new Connection object using the connection string
      Dim objConnect As New SqlConnection(strConnect)

      'create a new Command using the connection object and select statement
      Dim objCommand As New SqlCommand(strSelect, objConnect)

      'declare a variable to hold an XmlTextReader object
      Dim objXTReader As XmlTextReader

      'open the connection to the database
      objConnect.Open()

      'execute the SQL statement against the command to fill the XmlReader
      objXTReader = objCommand.ExecuteXmlReader()

      'read the first result to initialize the reader
      objXTReader.Read()

      'and then read remainder into the StringBuilder as well
      objStrBuilder.Append(objXTReader.GetRemainder().ReadToEnd())

      'close the XmlReader and Connection
      objXTReader.Close()
      objConnect.Close()

   Catch objError As Exception

      'display error details
      outError.InnerHtml = "<b>* Error while accessing data</b>.<br />" _
          & objError.Message & "<br />" & objError.Source
      Exit Sub  ' and stop execution

   End Try

   'display the results as Text to show XML elements
   outError.InnerText = objStrBuilder.ToString()

End Sub
</script>


<!--------------------------------------------------------------------------->
<!-- #include file="..\global\foot.inc" -->
</body>
</html>
